package org.x.yuenovel.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.x.yuenovel.controller.dto.CaptchaDTO;
import org.x.yuenovel.controller.dto.ResultDTO;
import org.x.yuenovel.controller.param.SendEmailCaptchaParam;
import org.x.yuenovel.enums.ResultCodeEnum;
import org.x.yuenovel.util.CaptchaUtil;
import org.x.yuenovel.util.EmailUtil;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author xuezhendong
 * @date 2022/4/21 9:12 下午
 */
@RestController
@Slf4j
@RequestMapping("captcha")
public class CaptchaController {

    @Resource
    private CaptchaUtil captchaUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private EmailUtil emailUtil;

    @PostMapping("getCaptcha")
    public ResultDTO<CaptchaDTO> captcha() {
        return ResultDTO.success(captchaUtil.getCaptchaCode());
    }

    @PostMapping("sendMailCaptcha")
    public ResultDTO<String> getMailCaptcha(@RequestBody @Validated SendEmailCaptchaParam param) {
        String captchaKey = param.getCaptchaKey();
        String captchaCode = stringRedisTemplate.opsForValue().get(captchaKey);
        if (ObjectUtils.isEmpty(captchaCode)) {
            return ResultDTO.error(ResultCodeEnum.CAPTCHA_EP);
        }
        if (ObjectUtils.isEmpty(param.getCaptchaCode()) || !Objects.equals(captchaCode,
                param.getCaptchaCode())) {
            return ResultDTO.error(ResultCodeEnum.CAPTCHA_ERROR);
        }
        emailUtil.senEmailCaptcha4Register(param.getMail());
        return ResultDTO.success("success");
    }
}
